package com.example.eat.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.eat.database.RecipeDatabaseHelper;
import com.example.eat.model.Recipe;
import java.util.ArrayList;
import java.util.List;

public class RecipeDao {
    private RecipeDatabaseHelper dbHelper;

    public RecipeDao(Context context) {
        dbHelper = new RecipeDatabaseHelper(context);
    }

    // 添加食谱
    public long addRecipe(Recipe recipe) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(RecipeDatabaseHelper.COLUMN_NAME, recipe.getName());
        values.put(RecipeDatabaseHelper.COLUMN_IMAGE, recipe.getImage());
        values.put(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS, recipe.getInstructions());
        values.put(RecipeDatabaseHelper.COLUMN_CATEGORY, recipe.getCategory());
        // 确保保存用户ID
        values.put(RecipeDatabaseHelper.COLUMN_USER_ID, recipe.getUserId());

        long id = db.insert(RecipeDatabaseHelper.TABLE_RECIPES, null, values);
        db.close();
        return id;
    }

    // 更新食谱
    public int updateRecipe(Recipe recipe) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(RecipeDatabaseHelper.COLUMN_NAME, recipe.getName());
        values.put(RecipeDatabaseHelper.COLUMN_IMAGE, recipe.getImage());
        values.put(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS, recipe.getInstructions());
        values.put(RecipeDatabaseHelper.COLUMN_CATEGORY, recipe.getCategory());
        // 确保保存用户ID
        values.put(RecipeDatabaseHelper.COLUMN_USER_ID, recipe.getUserId());

        String selection = RecipeDatabaseHelper.COLUMN_ID + " = ?";
        String[] selectionArgs = {String.valueOf(recipe.getId())};

        int count = db.update(
                RecipeDatabaseHelper.TABLE_RECIPES,
                values,
                selection,
                selectionArgs
        );

        db.close();
        return count;
    }

    // 删除食谱
    public int deleteRecipe(int recipeId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String selection = RecipeDatabaseHelper.COLUMN_ID + " = ?";
        String[] selectionArgs = {String.valueOf(recipeId)};

        // 先删除相关的收藏记录
        String favSelection = RecipeDatabaseHelper.COLUMN_FAV_RECIPE_ID + " = ?";
        db.delete(RecipeDatabaseHelper.TABLE_FAVORITES, favSelection, selectionArgs);

        // 再删除食谱
        int count = db.delete(
                RecipeDatabaseHelper.TABLE_RECIPES,
                selection,
                selectionArgs
        );

        db.close();
        return count;
    }

    // 获取指定ID的食谱
    public Recipe getRecipeById(int recipeId) {
        Recipe recipe = null;
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String[] projection = {
                RecipeDatabaseHelper.COLUMN_ID,
                RecipeDatabaseHelper.COLUMN_NAME,
                RecipeDatabaseHelper.COLUMN_IMAGE,
                RecipeDatabaseHelper.COLUMN_INSTRUCTIONS,
                RecipeDatabaseHelper.COLUMN_CATEGORY,
                RecipeDatabaseHelper.COLUMN_USER_ID
        };

        String selection = RecipeDatabaseHelper.COLUMN_ID + " = ?";
        String[] selectionArgs = {String.valueOf(recipeId)};

        Cursor cursor = db.query(
                RecipeDatabaseHelper.TABLE_RECIPES,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        if (cursor.moveToFirst()) {
            recipe = new Recipe();
            recipe.setId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_ID)));
            recipe.setName(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_NAME)));
            recipe.setImage(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_IMAGE)));
            recipe.setInstructions(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS)));
            recipe.setCategory(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_CATEGORY)));
            recipe.setUserId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_USER_ID)));
        }

        cursor.close();
        db.close();
        return recipe;
    }

    // 获取所有食谱
    public List<Recipe> getAllRecipes() {
        List<Recipe> recipeList = new ArrayList<>();
        String selectQuery = "SELECT * FROM " + RecipeDatabaseHelper.TABLE_RECIPES;

        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Recipe recipe = new Recipe();
                recipe.setId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_ID)));
                recipe.setName(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_NAME)));
                recipe.setImage(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_IMAGE)));
                recipe.setInstructions(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS)));
                recipe.setCategory(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_CATEGORY)));
                recipe.setUserId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_USER_ID)));

                recipeList.add(recipe);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return recipeList;
    }

    // 获取当前用户的所有食谱
    public List<Recipe> getMyRecipes(int userId) {
        List<Recipe> recipeList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String[] projection = {
                RecipeDatabaseHelper.COLUMN_ID,
                RecipeDatabaseHelper.COLUMN_NAME,
                RecipeDatabaseHelper.COLUMN_IMAGE,
                RecipeDatabaseHelper.COLUMN_INSTRUCTIONS,
                RecipeDatabaseHelper.COLUMN_CATEGORY,
                RecipeDatabaseHelper.COLUMN_USER_ID
        };

        String selection = RecipeDatabaseHelper.COLUMN_USER_ID + " = ?";
        String[] selectionArgs = {String.valueOf(userId)};

        Cursor cursor = db.query(
                RecipeDatabaseHelper.TABLE_RECIPES,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        if (cursor.moveToFirst()) {
            do {
                Recipe recipe = new Recipe();
                recipe.setId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_ID)));
                recipe.setName(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_NAME)));
                recipe.setImage(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_IMAGE)));
                recipe.setInstructions(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS)));
                recipe.setCategory(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_CATEGORY)));
                recipe.setUserId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_USER_ID)));

                recipeList.add(recipe);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return recipeList;
    }

    // 搜索食谱
    public List<Recipe> searchRecipes(String keyword) {
        List<Recipe> recipeList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String[] projection = {
                RecipeDatabaseHelper.COLUMN_ID,
                RecipeDatabaseHelper.COLUMN_NAME,
                RecipeDatabaseHelper.COLUMN_IMAGE,
                RecipeDatabaseHelper.COLUMN_INSTRUCTIONS,
                RecipeDatabaseHelper.COLUMN_CATEGORY,
                RecipeDatabaseHelper.COLUMN_USER_ID
        };

        String selection = RecipeDatabaseHelper.COLUMN_NAME + " LIKE ? OR " +
                RecipeDatabaseHelper.COLUMN_CATEGORY + " LIKE ?";
        String[] selectionArgs = {"%" + keyword + "%", "%" + keyword + "%"};

        Cursor cursor = db.query(
                RecipeDatabaseHelper.TABLE_RECIPES,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        if (cursor.moveToFirst()) {
            do {
                Recipe recipe = new Recipe();
                recipe.setId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_ID)));
                recipe.setName(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_NAME)));
                recipe.setImage(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_IMAGE)));
                recipe.setInstructions(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS)));
                recipe.setCategory(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_CATEGORY)));
                recipe.setUserId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_USER_ID)));

                recipeList.add(recipe);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return recipeList;
    }

    // 检查食谱是否被用户收藏
    public boolean isRecipeFavorite(int userId, int recipeId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String[] projection = {
                RecipeDatabaseHelper.COLUMN_FAV_USER_ID
        };

        String selection = RecipeDatabaseHelper.COLUMN_FAV_USER_ID + " = ? AND " +
                RecipeDatabaseHelper.COLUMN_FAV_RECIPE_ID + " = ?";
        String[] selectionArgs = {String.valueOf(userId), String.valueOf(recipeId)};

        Cursor cursor = db.query(
                RecipeDatabaseHelper.TABLE_FAVORITES,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        boolean isFavorite = cursor.moveToFirst();
        cursor.close();
        db.close();
        return isFavorite;
    }

    // 添加收藏
    public boolean addFavorite(int userId, int recipeId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(RecipeDatabaseHelper.COLUMN_FAV_USER_ID, userId);
        values.put(RecipeDatabaseHelper.COLUMN_FAV_RECIPE_ID, recipeId);

        long id = db.insert(RecipeDatabaseHelper.TABLE_FAVORITES, null, values);
        db.close();
        return id != -1;
    }

    // 移除收藏
    public boolean removeFavorite(int userId, int recipeId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String selection = RecipeDatabaseHelper.COLUMN_FAV_USER_ID + " = ? AND " +
                RecipeDatabaseHelper.COLUMN_FAV_RECIPE_ID + " = ?";
        String[] selectionArgs = {String.valueOf(userId), String.valueOf(recipeId)};

        int count = db.delete(
                RecipeDatabaseHelper.TABLE_FAVORITES,
                selection,
                selectionArgs
        );

        db.close();
        return count > 0;
    }

    // 获取用户的所有收藏食谱
    public List<Recipe> getFavoriteRecipes(int userId) {
        List<Recipe> favoriteRecipes = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // 使用JOIN查询获取用户收藏的食谱
        String query = "SELECT r.* FROM " + RecipeDatabaseHelper.TABLE_RECIPES + " r " +
                "JOIN " + RecipeDatabaseHelper.TABLE_FAVORITES + " f " +
                "ON r." + RecipeDatabaseHelper.COLUMN_ID + " = f." + RecipeDatabaseHelper.COLUMN_FAV_RECIPE_ID + " " +
                "WHERE f." + RecipeDatabaseHelper.COLUMN_FAV_USER_ID + " = ?";

        Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(userId)});

        if (cursor.moveToFirst()) {
            do {
                Recipe recipe = new Recipe();
                recipe.setId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_ID)));
                recipe.setName(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_NAME)));
                recipe.setImage(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_IMAGE)));
                recipe.setInstructions(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_INSTRUCTIONS)));
                recipe.setCategory(cursor.getString(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_CATEGORY)));
                recipe.setUserId(cursor.getInt(cursor.getColumnIndex(RecipeDatabaseHelper.COLUMN_USER_ID)));

                // 标记为收藏状态
                recipe.setFavorite(true);

                favoriteRecipes.add(recipe);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return favoriteRecipes;
    }
}